<form class="form-horizontal" id="ae_form"  method=POST enctype=multipart/form-data  role="form">
<input type="hidden" name="id" value="{{pageData['dao'].id}}"/>
<!-- TAB 1 -->

<ul class="nav nav-tabs" role="tablist" id="myTab">
  <li class="active"><a href="#dataPrincipali" role="tab" data-toggle="tab">Dati principali</a></li>
  <li><a href="#percorsoSegnalazione" role="tab" data-toggle="tab">Storico</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="dataPrincipali">
      <br />
      <div class="form-group">
            <label class="col-sm-3 col-lg-3 control-label" >Numero:</label>
            <div class="col-sm-9 col-lg-9">
                <p class="form-control-static">{{pageData["dao"].numero|nonone}}</p>
            </div>
        </div>
        <div class="form-group" title="">
            <label class="col-sm-3 col-lg-3 control-label" for="denominazione">Titolo:</label>
            <div class="col-sm-9 col-lg-9">
                <input class="form-control" type="text" id="denominazione" name="denominazione" value='{{pageData["dao"].denominazione|nonone}}' />
            </div>
        </div>
            <div class="form-group">
                <label class="col-sm-3 col-lg-3 control-label" for="id_tipo_segnalazione" >Argomento:</label>
                <div class="col-sm-9 col-lg-9">
                    <select id="id_tipo_segnalazione" name="id_tipo_segnalazione" class="validate[required]">
                        {% for t in pageData['tiposegnalazione'] %}
                            <option value="{{t.id}}" {{ 'selected="selected"' if t.id == pageData["dao"].id_tipo_segnalazione}}  >{{t.denominazione}} </option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 col-lg-3 control-label" for="id_tipo_segnalazione" >Priorità:</label>
                <div class="col-sm-9 col-lg-9">
                    <select id="id_priorita_segnalazione" name="id_priorita_segnalazione" class="validate[required]">
                        {% for t in pageData['prioritasegnalazione'] %}
                            <option value="{{t.id}}" {{ 'selected="selected"' if t.id == pageData["dao"].id_priorita_segnalazione}}  >{{t.denominazione}} </option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group" title="">
                <label class="col-sm-3 col-lg-3 control-label" for="descrizione">Descrizione:</label>
                <div class="col-sm-9 col-lg-9">
                    <textarea class="form-control" type="text" id="descrizione "name="descrizione" rows=10" cols="45">{{pageData['dao'].descrizione|nonone}}</textarea>
                </div>
            </div>
            <div class="form-group" title="">
                <label class="col-sm-3 col-lg-3 control-label" for="immagine">Immagine allegata:</label>
                <div class="col-sm-9 col-lg-9">
                       <span class="btn btn-success fileinput-button">
                            <i class="glyphicon glyphicon-plus"></i>
                            <span>Add files...</span>
        <!-- The file input field used as target for the file upload widget -->
        <input id="fileupload" type="file" name="file" multiple>
    </span>
        <!-- The global progress bar -->
    <div id="progress" class="progress">
        <div class="progress-bar progress-bar-success"></div>
    </div>
    <!-- The container for the uploaded files -->
    <div id="files" class="files"></div>
    <br>
            </div>
            </div>
                        <div class="form-group" title="">
                <label class="col-sm-3 col-lg-3 control-label" for="descrizione">Geo:</label>
                         <div class="col-sm-9 col-lg-9 ri item">
                            <div id="map_canvas" class="map-short rounded"></div>
                           <input type="hidden" name="maplat" id="lat" value="55.000000" />
                            <input type="hidden" name="maplng" id="lng" value="20.000000" />
                            </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 col-lg-3 control-label" for="id_stato_segnalazione" >Stato :</label>
                <div class="col-sm-9 col-lg-9">
                    <select id="id_stato_segnalazione" name="id_stato_segnalazione" {{ 'disabled"'  if pageData["oper"] and pageData["oper"].tipo_operatore|lower == "amministratore" }} class="validate[required]">
                        {% for t in pageData['statosegnalazione'] %}
                            <option value="{{t.id}}" {{ 'selected="selected"' if t.id == pageData["dao"].id_stato_segnalazione}}  >{{t.denominazione}} </option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group" title="">
                <label class="col-sm-3 col-lg-3 control-label" for="descrizione">Note del cambiamento:</label>
                <div class="col-sm-9 col-lg-9">
                    <textarea class="form-control" type="text" id="note "name="note" rows="10" cols="45"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 col-lg-3 control-label" >Data inserimento:</label>
                <div class="col-sm-9 col-lg-9">
                    <p class="form-control-static">{{pageData["dao"].registration_date|nonone|datetimeformat}}</p>
                </div>
            </div>




  </div>
  <div class="tab-pane" id="percorsoSegnalazione">
    <br /><br /> <br />

  <div class="infinite-container">
        {% for a in pageData["percorso"] %}
        <div class="infinite-itemmm">
<div class="row">
    <div class="col-xs-12 col-md-12 col-lg-12 col-sm-12">
        <div class="panel panel-danger">
            <div class="panel-heading">
                [#{{pageData["dao"].numero}}] <strong>{{a.data_modifica|datetimeformat}}</strong>
            </div>
        <div class="panel-body">
                <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Tipo:</b> {{ a.tipo_segnalazione|nonone }}</div>
                 </div>
                 <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Priorità:</b> {{ a.priorita_segnalazione|nonone }}</div>
                 </div>
                 <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Stato:</b> {{ a.stato_segnalazione|nonone }}</div>
                 </div>
                <div class="row">
                    <div class="col-sm-12 col-lg-12"><b>Operatore:</b> {{ a.operatore|nonone }}</div>
                 </div>
        </div>
        <div class="panel-footer">
            <b>Note:</b> {{ a.note|nonone }}
        </div>
        </div>
    </div>
</div>
</div>
        {% endfor %}

{% if pageData['page'] != 0 %}
    <a href="/italiaCives/segnalazioni/{{pageData['page']}}" class="infinite-more-link"></a>
{% endif %}
</div>

  </div>

</div>



<div class="form-group" title="Bottoni di salvataggio e reset del form">
        <div class="col-sm-5 col-lg-5 col-sm-offset-2">
            <input class="btn btn-primary" type="submit" value="Salva" name="add"/>
<!--
            <input class="btn btn-danger" type="button" data-dismiss="modal" value="Chiudi" name="chiudi" id="chiudi_edit"/>
-->
        </div>
    </div>

</form>


<script>
$(document).ready(function(){

//navigator.geolocation.getCurrentPosition(
    //gotPosition,
    //errorGettingPosition,
    //{'enableHighAccuracy':true,'timeout':10000,'maximumAge':0}
    //);

$(function () {
    'use strict';
    alert(window.location.hostname);
    // Change this to the location of your server-side upload handler:
        var url = '/italiaCives/segnalazione/Create',

        uploadButton = $('<button/>')
            .addClass('btn btn-primary')
            .prop('disabled', true)
            .text('Processing...')
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Abort')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit().always(function () {
                    $this.remove();
                });
            });
    $('#fileupload').fileupload({
        url: "",
        dataType: 'json',
        autoUpload: false,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 5000000, // 5 MB
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 100,
        previewMaxHeight: 100,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        data.context = $('<div/>').appendTo('#files');
        $.each(data.files, function (index, file) {
            var node = $('<p/>')
                    .append($('<span/>').text(file.name));
            if (!index) {
                node
                    .append('<br>')
                    .append(uploadButton.clone(true).data(data));
            }
            node.appendTo(data.context);
        });
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
        if (file.preview) {
            node
                .prepend('<br>')
                .prepend(file.preview);
        }
        if (file.error) {
            node
                .append('<br>')
                .append($('<span class="text-danger"/>').text(file.error));
        }
        if (index + 1 === data.files.length) {
            data.context.find('button')
                .text('Upload')
                .prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress .progress-bar').css(
            'width',
            progress + '%'
        );
    }).on('fileuploaddone', function (e, data) {
        $.each(data.result.files, function (index, file) {
            if (file.url) {
                var link = $('<a>')
                    .attr('target', '_blank')
                    .prop('href', file.url);
                $(data.context.children()[index])
                    .wrap(link);
            } else if (file.error) {
                var error = $('<span class="text-danger"/>').text(file.error);
                $(data.context.children()[index])
                    .append('<br>')
                    .append(error);
            }
        });
    }).on('fileuploadfail', function (e, data) {
        $.each(data.files, function (index, file) {
            var error = $('<span class="text-danger"/>').text('File upload failed.');
            $(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});
// FINE UPLOAD IMMAGINI


$('#myTab').click(function (e) {
  e.preventDefault()
  $(this).tab('show')
})
//$( "#ae_form" ).validationEngine({
                    //prettySelect : true,
                    //useSuffix: "_chosen",
                //});
$( "#id_tipo_segnalazione" ).chosen({
                    width: '50%',
                    disable_search:true,
                    allow_single_deselect: true})
$( "#id_priorita_segnalazione" ).chosen({
                    width: '50%',
                    disable_search:true,
                    allow_single_deselect: true})
$( "#id_stato_segnalazione" ).chosen({
                    width: '50%',
                    disable_search:true,
                    allow_single_deselect: true})




function gotPosition(pos)  {
        var outputStr =
            "latitude:"+ pos.coords.latitude +"\n"+
            "longitude:"+ pos.coords.longitude +"\n"+
            "accuracy:"+ pos.coords.accuracy +"\n"+

            "altitude:"+ pos.coords.altitude +"\n"+
            "altitudeAccuracy:"+ pos.coords.altitudeAccuracy +"\n"+
            "heading:"+ pos.coords.heading +"\n"+
            "speed:"+ pos.coords.speed +"";

            //alert(outputStr);
            $('input#lat').val( pos.coords.latitude );
            $('input#lng').val( pos.coords.longitude );
    $("#map_canvas").gmap3({
        marker:{
            values:[ {latLng:[pos.coords.latitude,pos.coords.longitude]}],
            options:{draggable: true },
            events:{
                dragend: function(marker, event){
                $('input#lat').val( marker.position.lat() );
                $('input#lng').val( marker.position.lng() );
                        $(this).gmap3({
          getaddress:{
            latLng:marker.getPosition(),
            callback:function(results){
              var map = $(this).gmap3("get"),
                infowindow = $(this).gmap3({get:"infowindow"}),
                content = results && results[1] ? results && results[1].formatted_address : "no address";
              if (infowindow){
                infowindow.open(map, marker);
                infowindow.setContent(content);
              } else {
                $(this).gmap3({
                  infowindow:{
                    anchor:marker,
                    options:{content: content}
                  }
                });
              }
            }
          }
        });
                }
            },
            },

        map:{
        options:{ zoom: 14 }
        }
        });
    }

function errorGettingPosition(err) {
        if(err.code == 1) {
            alert("L'utente non ha autorizzato la geolocalizzazione");
        } else if(err.code == 2) {
            alert("Posizione non disponibile");
        } else if(err.code == 3) {
            alert("Timeout");
        } else {
            alert("ERRORE:" + err.message);
        }
    }

 });
</script>
